package com.mmd.manage.web;

import com.alibaba.fastjson.JSON;
import com.mmd.bean.CODE;
import com.mmd.bean.UserLoginContext;
import com.mmd.bean.WebJsonBean;
import com.mmd.common.entity.MmdRouteDetail;
import com.mmd.exception.GameException;
import com.mmd.intercepter.AdminInterceptor;
import com.mmd.manage.service.RouteService;
import com.mmd.manage.service.SupplierService;
import com.mmd.manage.vo.RouteVo;
import com.mmd.manage.vo.SupplierVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@RequestMapping(value = "/api/route")
@Controller
public class RouteController {
    private static Logger logger = LoggerFactory.getLogger(RouteController.class);
    @Autowired
    private RouteService routeService;
    @Autowired
    private SupplierService supplierService;

    @RequestMapping(value = "/getRouteNameList")
    @ResponseBody
    public WebJsonBean getRouteNameList() {
        logger.info("登录态：{}", JSON.toJSONString(AdminInterceptor.getUserLoginContext()));
        long uid = AdminInterceptor.getUserLoginContext().getUid();
        return new WebJsonBean(CODE.SUCCESS, routeService.getRouteNameList(uid));
    }

    /**
     * 查找路线的有效时间列表
     * @return
     */
    @RequestMapping(value = "/getValidTimeByRouteName")
    @ResponseBody
    public WebJsonBean getValidTimeByRouteName(String routeName, Long modeId, Long areaId){
        return new WebJsonBean(CODE.SUCCESS, routeService.getValidTimeByRouteName(routeName));
    }


    @RequestMapping(value = "/getRouteList")
    @ResponseBody
    public WebJsonBean getRouteList(String supplierCode) {
        return new WebJsonBean(CODE.SUCCESS, routeService.getRouteList(supplierCode));
    }


    @RequestMapping(value = "/addRoute")
    @ResponseBody
    public WebJsonBean addRoute(String supplierCode, String routeName, Long modeId, Long areaId, String isem, String detailJson,
                                String hscodeJson, String validStartTimeStr, String validEndTimeStr) {
        UserLoginContext context = AdminInterceptor.getUserLoginContext();
        if ("admin".equals(context.getLevel())) {
            if (StringUtils.isEmpty(supplierCode)) {
                throw new GameException(new CODE(9999, "请选择供应商"));
            }
        } else {
            long uid = context.getUid();
            SupplierVo supplier = supplierService.getSupplierDetailByUid(uid);
            if (supplier == null) {
                throw new GameException(new CODE(9999, "账号异常"));
            }
            supplierCode = supplier.getSupplierCode();
        }
        if (StringUtils.isEmpty(routeName)) {
            throw new GameException(new CODE(9999, "请填写渠道路线名称"));
        }
        if (modeId == null) {
            throw new GameException(new CODE(9999, "请选择模式"));
        }
        if (areaId == null) {
            throw new GameException(new CODE(9999, "请选择区域"));
        }
        if (StringUtils.isEmpty(detailJson)) {
            throw new GameException(new CODE(9999, "请填写渠道路线详情"));
        }
        if (StringUtils.isEmpty(validStartTimeStr)) {
            throw new GameException(new CODE(9999, "请填写开始生效时间"));
        }
        if (StringUtils.isEmpty(validEndTimeStr)) {
            throw new GameException(new CODE(9999, "请填写开始生效时间"));
        }
        routeService.addRoute(supplierCode, routeName, modeId, areaId, isem, detailJson, hscodeJson, validStartTimeStr, validEndTimeStr);
        return new WebJsonBean(CODE.SUCCESS);
    }

    @RequestMapping(value = "/modifyRoute")
    @ResponseBody
    public WebJsonBean modifyRoute(String routeNo, String routeName, Long modeId, Long areaId, String isem, String detailJson,
                                   String hscodeJson, String validStartTimeStr, String validEndTimeStr) {
        if (StringUtils.isEmpty(routeNo)) {
            throw new GameException(new CODE(9999, "请选择渠道路线"));
        }
        if (StringUtils.isEmpty(routeName)) {
            throw new GameException(new CODE(9999, "请填写渠道路线名称"));
        }
        if (modeId == null) {
            throw new GameException(new CODE(9999, "请选择模式"));
        }
        if (areaId == null) {
            throw new GameException(new CODE(9999, "请选择区域"));
        }
        if (StringUtils.isEmpty(detailJson)) {
            throw new GameException(new CODE(9999, "请填写渠道路线详情"));
        }
        if (StringUtils.isEmpty(validStartTimeStr)) {
            throw new GameException(new CODE(9999, "请填写开始生效时间"));
        }
        if (StringUtils.isEmpty(validEndTimeStr)) {
            throw new GameException(new CODE(9999, "请填写开始生效时间"));
        }
        routeService.modifyRoute(routeNo, routeName, modeId, areaId, isem, detailJson, hscodeJson, validStartTimeStr, validEndTimeStr);
        return new WebJsonBean(CODE.SUCCESS);
    }

    @RequestMapping(value = "/getRouteInfo")
    @ResponseBody
    public WebJsonBean getRouteInfo(String routeNo) {
        if (StringUtils.isEmpty(routeNo)) {
            throw new GameException(new CODE(9999, "请选择渠道路线"));
        }
        return new WebJsonBean(CODE.SUCCESS, routeService.getRouteInfo(routeNo));
    }

    @RequestMapping(value = "/getModeList")
    @ResponseBody
    public WebJsonBean getModeList() {
        return new WebJsonBean(CODE.SUCCESS);
    }

    @RequestMapping(value = "/getAreaList")
    @ResponseBody
    public WebJsonBean getAreaList() {
        return new WebJsonBean(CODE.SUCCESS);
    }

    @RequestMapping(value = "/getHscodeList")
    @ResponseBody
    public WebJsonBean getHscodeList() {
        return new WebJsonBean(CODE.SUCCESS);
    }

    @RequestMapping(value = "/export")
    @ResponseBody
    public WebJsonBean export(HttpServletRequest request, HttpServletResponse response) {
        HSSFWorkbook wb = new HSSFWorkbook();

        String supplierName = "";
        long uid = AdminInterceptor.getUserLoginContext().getUid();
        List<RouteVo> routeVoList = routeService.getRouteListBySupplier(uid);
        // 填充数据
        for (int j = 1; j <= routeVoList.size(); j++) {
            RouteVo vo = routeVoList.get(j - 1);
            supplierName = vo.getSupplierName();
            // sheet 对应一个工作页
            Sheet sheet = wb.createSheet(vo.getRouteName());
            sheet.setDefaultColumnWidth(10);
            sheet.setDefaultRowHeightInPoints(20);
            // 创建第一行为标题行
            Row hssfRow = sheet.createRow(0);
            Cell hssfCell = hssfRow.createCell(0);
            String[] titleArr = {"路线名称", "模式", "区域", "21kg+", "46kg+", "71kg", "101kg", "301kg", "501kg", "1001kg", "提取时间", "单票操作费", "单票报关费", "中港"};
            int i = 0;
            /* for循环生成列名 */
            for (String key : titleArr) {
                hssfCell = hssfRow.createCell(i);
                hssfCell.setCellValue(key);
                i++;
            }

            List<MmdRouteDetail> detailList = vo.getRouteDetailList();
            for (int x = 1; x <= detailList.size(); x++) {
                MmdRouteDetail detail = detailList.get(x - 1);
                hssfRow = sheet.createRow(x);

                //路线名称
                hssfCell = hssfRow.createCell(0);
                hssfCell.setCellValue(vo.getRouteName());
                //模式
                hssfCell = hssfRow.createCell(1);
                hssfCell.setCellValue(vo.getModeName());
                //区域
                hssfCell = hssfRow.createCell(2);
                hssfCell.setCellValue(detail.getSonAreaName());
                //21kg+
                hssfCell = hssfRow.createCell(3);
                hssfCell.setCellValue(detail.getKg21().toString());
                //46kg+
                hssfCell = hssfRow.createCell(4);
                hssfCell.setCellValue(detail.getKg46().toString());
                //71kg
                hssfCell = hssfRow.createCell(5);
                hssfCell.setCellValue(detail.getKg71().toString());
                //101kg
                hssfCell = hssfRow.createCell(6);
                hssfCell.setCellValue(detail.getKg101().toString());
                //301kg
                hssfCell = hssfRow.createCell(7);
                hssfCell.setCellValue(detail.getKg301().toString());
                //501kg
                hssfCell = hssfRow.createCell(8);
                hssfCell.setCellValue(detail.getKg501().toString());
                //1001kg
                hssfCell = hssfRow.createCell(9);
                hssfCell.setCellValue(detail.getKg1001().toString());
                //提取时间
                hssfCell = hssfRow.createCell(10);
                hssfCell.setCellValue(detail.getDrawTime());
                //单票操作费
                hssfCell = hssfRow.createCell(11);
                hssfCell.setCellValue(detail.getSingleOperatFee().toString());
                //单票报关费
                hssfCell = hssfRow.createCell(12);
                hssfCell.setCellValue(detail.getSingleDeclareFee().toString());
                //中港
                hssfCell = hssfRow.createCell(13);
                hssfCell.setCellValue(detail.getZgFee().toString());
            }
//			for (int a = 0; a <= i; a++) {
//				sheet.autoSizeColumn(a);// 設置自動列寬
//			}
        }

        // 创建文件输出流，准备输出电子表格
        try {
            String fileName = supplierName + "路线-" + System.currentTimeMillis() + ".xls";
            String agent = request.getHeader("User-Agent");
            boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
            if (isMSIE) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF8");
            } else {
                //兼容火狐，否则中文乱码
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new WebJsonBean(CODE.SUCCESS);
    }
}
